# coding=utf-8
import traceback

import pymysql.cursors

# import servers

servers = [

    '172.16.3.56',
    '172.16.3.134',

]


def search_one(_ip, connection, sql):
    try:

        with connection.cursor() as cursor:
            # 执行sql语句，插入记录

            cursor.execute(sql)

            return cursor.fetchone()

    except BaseException, ex:
        print traceback.format_exc()
        print "执行失败了一台机器:" + _ip + ' 原因:' + ex.message
        return None
    finally:
        connection.commit()


def do_sql(_ip, connection, sql):
    try:

        with connection.cursor() as cursor:
            # 执行sql语句，插入记录

            cursor.execute(sql);

    except BaseException, ex:
        print traceback.format_exc()
        print "执行失败了一台机器:" + _ip + ' 原因:' + ex.message
    finally:
        connection.commit()


def deal_all_db():
    for ser in servers:
        _ip = ser



        config = {
            'host': _ip,
            'port': 3306,
            'user': 'root',
            'password': 'winit2015',
            'db': 'ucloud_agent',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor,
            'connect_timeout': 10
        }

        try:
            # Connect to the database
            connection = pymysql.connect(**config)

            if not allready_inserted(_ip=_ip, connection=connection,
                                     zone_code='uc.auaws.warehouse.auss'):
                print "开搞"
                pass;
                insert_zone(_ip=_ip, connection=connection,
                            zone_code='uc.auaws.warehouse.auss',
                            zone_alias='auss',
                            parent_code='uc.auaws.area',
                            title='澳洲存储仓',
                            order='32')
        except BaseException, ex:
            print ex.message

        finally:

            if connection is not None:
                try:
                    connection.close()
                except BaseException, ex:
                    print ex.message


def allready_inserted(_ip, connection, zone_code):
    sql = "SELECT 1 FROM ucloud_agent.zone zone where zone_code = '%s'" % zone_code

    result = search_one(_ip, connection, sql)

    if result is not None:
        return True
    else:
        return False


def insert_zone(_ip, connection, zone_code, zone_alias, parent_code, title,
                order):
    sql = "INSERT INTO ucloud_agent.zone (zone_code, zone_alias, parent_code, zone_title, zone_desc, available, home_path, build_in, created, updated, timezone, zone_alise, order_no) VALUES (" \
          "'%s', " \
          "'%s', " \
          "'%s', " \
          "'%s', " \
          "null, " \
          "1, " \
          "null, " \
          "0, " \
          "null, " \
          "null, " \
          "'', " \
          "null, " \
          "%s);" % (zone_code, zone_alias, parent_code, title, order)
    do_sql(_ip, connection, sql)


deal_all_db()
